/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 */
#include <rtthread.h>
#include <rtdevice.h>

#ifdef SPIFLASH_DBG_ENABLE
#define DBG_ENABLE
#endif
#define DBG_TAG "WQ25x"
#define DBG_LEVEL DBG_INFO
#include <rtdbg.h>

#ifndef SPIFLASH_BLOCK_NAME
#define SPIFLASH_BLOCK_NAME "nor0"
#endif

/* JEDEC Manufacturer’s ID */
#define MF_ID (0xEF)
/* JEDEC Device ID: Memory type and Capacity */
#define MTC_W25Q80_BV (0x4014)       /* W25Q80BV */
#define MTC_W25Q16_BV_CL_CV (0x4015) /* W25Q16BV W25Q16CL W25Q16CV  */
#define MTC_W25Q16_DW (0x6015)       /* W25Q16DW  */
#define MTC_W25Q32_BV (0x4016)       /* W25Q32BV */
#define MTC_W25Q32_DW (0x6016)       /* W25Q32DW */
#define MTC_W25Q64_BV_CV (0x4017)    /* W25Q64BV W25Q64CV */
#define MTC_W25Q64_DW (0x4017)       /* W25Q64DW */
#define MTC_W25Q128_BV (0x4018)      /* W25Q128BV */
#define MTC_W25Q256_FV (TBD)         /* W25Q256FV */

#define MTC_W25X80 (0x3014)

/* command list */
#define CMD_WRSR (0x01)       /* Write Status Register */
#define CMD_PP (0x02)         /* Page Program */
#define CMD_READ (0x03)       /* Read Data */
#define CMD_WRDI (0x04)       /* Write Disable */
#define CMD_RDSR1 (0x05)      /* Read Status Register-1 */
#define CMD_WREN (0x06)       /* Write Enable */
#define CMD_FAST_READ (0x0B)  /* Fast Read */
#define CMD_ERASE_4K (0x20)   /* Sector Erase:4K */
#define CMD_RDSR2 (0x35)      /* Read Status Register-2 */
#define CMD_ERASE_32K (0x52)  /* 32KB Block Erase */
#define CMD_JEDEC_ID (0x9F)   /* Read JEDEC ID */
#define CMD_ERASE_full (0xC7) /* Chip Erase */
#define CMD_ERASE_64K (0xD8)  /* 64KB Block Erase */
#define CMD_MANU_ID (0x90)

#define DUMMY (0xFF)

#define FLASH_ERASE_CMD CMD_ERASE_4K
#define FLASH_BLOCK_SIZE 4096
#define FLASH_PAGE_SIZE 256

#define GETSPI(d) ((struct rt_spi_device *)d->parent.priv)

static void w25qxx_lock(rt_nor_t *device)
{
    //struct spi_flash_mtd *mtd = (struct spi_flash_mtd *)device;
    //rt_mutex_take(&mtd->lock, RT_WAITING_FOREVER);
}

static void w25qxx_unlock(rt_nor_t *device)
{
    //struct spi_flash_mtd *mtd = (struct spi_flash_mtd *)device;
    //rt_mutex_release(&mtd->lock);
}

static rt_uint8_t w25qxx_read_status(rt_nor_t *device)
{
    struct rt_spi_device *rt_spi_device = GETSPI(device);

    return rt_spi_sendrecv8(rt_spi_device, CMD_RDSR1);
}

static void w25qxx_wait_busy(rt_nor_t *device)
{
    while (w25qxx_read_status(device) & (0x01))
        ;
}

static uint32_t w25qxx_read_id(rt_nor_t *device)
{
    uint8_t cmd;
    uint8_t id_recv[3] = {0};
    struct rt_spi_device *rt_spi_device = GETSPI(device);

    w25qxx_lock(device);

    cmd = 0xFF; /* reset SPI FLASH, cancel all cmd in processing. */
    rt_spi_send(rt_spi_device, &cmd, 1);

    cmd = CMD_WRDI;
    rt_spi_send(rt_spi_device, &cmd, 1);

    /* read flash id */
    cmd = CMD_JEDEC_ID;
    rt_spi_send_then_recv(rt_spi_device, &cmd, 1, id_recv, 3);

    w25qxx_unlock(device);

    return (uint32_t)(id_recv[0] << 16) | (id_recv[1] << 8) | id_recv[2];
}

static int w25qxx_read(rt_nor_t *device, loff_t offset, uint8_t *buffer, size_t length)
{
    rt_uint8_t send_buffer[4];
    struct rt_spi_device *rt_spi_device = GETSPI(device);

    w25qxx_lock(device);

    send_buffer[0] = CMD_WRDI;
    rt_spi_send(rt_spi_device, send_buffer, 1);

    send_buffer[0] = CMD_READ;
    send_buffer[1] = (rt_uint8_t)(offset >> 16);
    send_buffer[2] = (rt_uint8_t)(offset >> 8);
    send_buffer[3] = (rt_uint8_t)(offset);
    rt_spi_send_then_recv(rt_spi_device,
                          send_buffer, 4,
                          buffer, length);

    w25qxx_unlock(device);
    return length;
}

static int w25qxx_write(rt_nor_t *device, loff_t offset, const uint8_t *buffer, size_t length)
{
    uint8_t send_buffer[4];
    uint8_t *write_ptr;
    size_t write_size, write_total;
    struct rt_spi_device *rt_spi_device = GETSPI(device);

    w25qxx_lock(device);

    send_buffer[0] = CMD_WREN;
    rt_spi_send(rt_spi_device, send_buffer, 1);
    w25qxx_wait_busy(device); // wait erase done.

    write_size = 0;
    write_total = 0;
    write_ptr = (rt_uint8_t *)buffer;
    while (write_total < length)
    {
        send_buffer[0] = CMD_WREN;
        rt_spi_send(rt_spi_device, send_buffer, 1);

        //write first page...
        send_buffer[0] = CMD_PP;
        send_buffer[1] = (rt_uint8_t)(offset >> 16);
        send_buffer[2] = (rt_uint8_t)(offset >> 8);
        send_buffer[3] = (rt_uint8_t)(offset);

        //address % FLASH_PAGE_SIZE + length
        if (((offset & (FLASH_PAGE_SIZE - 1)) + (length - write_total)) > FLASH_PAGE_SIZE)
        {
            write_size = FLASH_PAGE_SIZE - (offset & (FLASH_PAGE_SIZE - 1));
        }
        else
        {
            write_size = (length - write_total);
        }

        rt_spi_send_then_send(rt_spi_device,
                              send_buffer, 4,
                              write_ptr + write_total, write_size);
        w25qxx_wait_busy(device);

        offset += write_size;
        write_total += write_size;
    }

    send_buffer[0] = CMD_WRDI;
    rt_spi_send(rt_spi_device, send_buffer, 1);

    w25qxx_unlock(device);

    return length;
}

static int w25qxx_erase_block(rt_nor_t *device, loff_t offset, size_t length)
{
    uint8_t send_buffer[4];
    uint32_t erase_size = 0;
    struct rt_spi_device *rt_spi_device = GETSPI(device);

    w25qxx_lock(device);

    send_buffer[0] = CMD_WREN;
    rt_spi_send(rt_spi_device, send_buffer, 1);
    w25qxx_wait_busy(device); // wait erase done.
    while (erase_size < length)
    {
        send_buffer[0] = CMD_ERASE_4K;
        send_buffer[1] = (rt_uint8_t)(offset >> 16);
        send_buffer[2] = (rt_uint8_t)(offset >> 8);
        send_buffer[3] = (rt_uint8_t)(offset);
        rt_spi_send(rt_spi_device, send_buffer, 4);
        w25qxx_wait_busy(device); // wait erase done.

        erase_size += 4096;
        offset += 4096;
    }
    send_buffer[0] = CMD_WRDI;
    rt_spi_send(rt_spi_device, send_buffer, 1);

    w25qxx_unlock(device);
    return RT_EOK;
}

static const struct nor_ops w25qxx_mtd_ops =
{
    w25qxx_erase_block,
    w25qxx_read,
    w25qxx_write,
};

int w25qxx_mtd_init(const char *mtd_name, const char *spi_device_name)
{
    int result = 0;
    uint32_t id;
    uint8_t send_buffer[3];
    struct rt_spi_device *rt_spi_device;
    uint32_t size = 0;
    rt_nor_t *mtd = (rt_nor_t *)rt_malloc(sizeof(*mtd));

    RT_ASSERT(mtd != RT_NULL);

    rt_spi_device = (struct rt_spi_device *)rt_device_find(spi_device_name);
    if (rt_spi_device == RT_NULL)
    {
        LOG_E("spi device %s not found!\r\n", spi_device_name);
        result = -1;

        goto _error_exit;
    }
    mtd->parent.priv = rt_spi_device;
    /* config spi */
    {
        struct rt_spi_configuration cfg;
        cfg.data_width = 8;
        cfg.mode = RT_SPI_MODE_0 | RT_SPI_MSB; /* SPI Compatible: Mode 0 and Mode 3 */
        cfg.max_hz = 20 * 1000 * 1000;         /* 20 */
        rt_spi_configure(rt_spi_device, &cfg);
    }

    /* Init Flash device */
    {
        w25qxx_lock(mtd);

        send_buffer[0] = CMD_WREN;
        rt_spi_send(rt_spi_device, send_buffer, 1);
        w25qxx_wait_busy(mtd);

        send_buffer[0] = CMD_WRSR;
        send_buffer[1] = 0;
        send_buffer[2] = 0;
        rt_spi_send(rt_spi_device, send_buffer, 3);
        w25qxx_wait_busy(mtd);

        w25qxx_unlock(mtd);
    }

    id = w25qxx_read_id(mtd);
    if (id == 0)
        goto _error_exit;

    switch (id & 0xFFFF)
    {
    case MTC_W25Q80_BV: /* W25Q80BV */
        size = 256 * 4096;
        break;
    case MTC_W25Q16_BV_CL_CV: /* W25Q16BV W25Q16CL W25Q16CV  */
    case MTC_W25Q16_DW:       /* W25Q16DW  */
        size = 512 * 4096;
        break;
    case MTC_W25Q32_BV: /* W25Q32BV */
    case MTC_W25Q32_DW: /* W25Q32DW */
        size = 1024 * 4096;
        break;
    case MTC_W25Q64_BV_CV: /* W25Q64BV W25Q64CV */
        size = 2048 * 4096;
        break;
    case MTC_W25Q128_BV: /* W25Q128BV */
        size = 4086 * 4096;
        break;
    }

    mtd->ops = &w25qxx_mtd_ops;
    rt_mtd_nor_init(mtd, 4096);
    {
        struct mtd_part p;

        p.name = mtd_name;
        p.offset = 0;
        p.size = size;

        result = rt_mtd_register(&mtd->parent, &p, 1);
    }

    return 0;

_error_exit:
    if (mtd != RT_NULL)
        rt_free(mtd);

    return result;
}

static int _spi_bus_attach_device(int cspin, int active_level, const char *bus_name, const char *device_name)
{
    struct rt_spi_device *spi_device = (struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
    RT_ASSERT(spi_device != RT_NULL);

    spi_device->cs_pin = cspin;
    spi_device->cs_active = active_level;

    rt_pin_mode(cspin, PIN_MODE_OUTPUT);
    rt_pin_write(cspin, !active_level);

    return rt_spi_bus_attach_device(spi_device, device_name, bus_name, 0);
}

int w25qxx_flash_init(void)
{
    int cspin;
    int ret;

    cspin = rt_pin_get(SPIFLASH_CSPIN_NAME);
    if (cspin < 0)
    {
        return -1;
    }

    if (_spi_bus_attach_device(cspin, SPIFLASH_CSPIN_ACTIVE, SPIFLASH_SPIBUS_NAME, SPIFLASH_SPIDEV_NAME) != 0)
    {
        return -1;
    }

    ret = w25qxx_mtd_init(SPIFLASH_BLOCK_NAME, SPIFLASH_SPIDEV_NAME);

    return ret;
}
INIT_DEVICE_EXPORT(w25qxx_flash_init);
